﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Reflection;
using System.Web.Security;
using System.IO;
using System.IO.Compression;

namespace Folks.Handlers
{
	public class FolksResourceLoader : IHttpHandler
	{
		#region IHttpHandler Members

		public bool IsReusable
		{
			get { return true; }
		}

		public void ProcessRequest(HttpContext context)
		{
			EnsureRequestParameters(context);
			Assembly asm = typeof(FolksResourceLoader).Assembly;
			string resourceName = GetResourceName(asm, context);
			if (context.Cache["Folks" + resourceName] == null)
			{
				object resource = new StreamReader(asm.GetManifestResourceStream(resourceName)).ReadToEnd();
				context.Cache["Folks" + resourceName] = resource;
				context.Response.Write(resource);
			}
			else
				context.Response.Write(context.Cache["Folks" + resourceName]);
		}
		#endregion

		#region Instance Methods
		private string GetResourceName(Assembly asm, HttpContext context)
		{
			string resourceName = Array.Find<string>
			(
				asm.GetManifestResourceNames(),
				delegate(string r)
				{
					return FormsAuthentication.HashPasswordForStoringInConfigFile(r, "SHA1") == context.Request["r"];
				}
			);

			if (string.IsNullOrEmpty(resourceName))
				throw new HttpException(404, "Resource not found!");
			return resourceName;
		}

		private void EnsureRequestParameters(HttpContext context)
		{
			if (string.IsNullOrEmpty(context.Request["r"]))
				throw new HttpException(404, "Resource not found!");
		}
		#endregion

		#region Static Methods
		public static string GetResourceUrl(string resource)
		{
			Assembly asm = typeof(FolksResourceLoader).Assembly;
			if (Contains(asm, resource))
				return "FolksResource.ashx?r=" + FormsAuthentication.HashPasswordForStoringInConfigFile(resource, "SHA1");
			return string.Empty;
		}

		private static bool Contains(Assembly asm, string resource)
		{
			return Array.Find<string>(asm.GetManifestResourceNames(), delegate(string r) { return r == resource; }) != null;
		}
		#endregion
	}
}
